<template>
  <div
    ref="parent"
    class="group relative p-0.5 rounded-sm border-gray-300 dark:border-zinc-600 dark:bg-zinc-800 duration-300 hover:bg-gray-100/60 dark:hover:bg-zinc-700"
  >
    <div>
      <!-- 搜索图标 -->
      <My-svg-icon
        class="w-1.5 h-1.5 absolute translate-y-[-50%] top-[50%] left-2"
        name="search"
        color="#909090"
      />
      <!-- 输入框 -->
      <input
        @focus="onFocus"
        class="block w-[85vw] h-[44px] pl-4 text-sm outline-0 bg-transparent caret-gray-500 text-gray-800 dark:text-zinc-200 placeholder-gray-500 dark:placeholder-zinc-400 tracking-wide font-medium border border-gray-300 duration-300 group-hover:bg-white dark:group-hover:bg-zinc-700 group-hover:border-gray-400 dark:group-hover:border-zinc-500 focus:border-blue-400 dark:focus:border-zinc-800"
        type="text"
        v-model.trim="useNavigationStore.currentSearchValue"
        placeholder="搜索本站文章"
      />
      <!-- 删除按钮 -->
      <My-svg-icon
        @click="useNavigationStore.currentSearchValue = ''"
        name="input-delete"
        class="h-1.5 w-1.5 absolute translate-y-[-50%] top-[50%] right-9 duration-300 cursor-pointer text-gray-500 hover:text-gray-700 dark:text-zinc-400 dark:hover:text-zinc-300"
      />
      <!-- 分割线 -->
      <div
        class="opacity-0 h-1.5 w-[1px] absolute translate-y-[-50%] top-[50%] right-[80px] duration-300 bg-gray-300 dark:bg-zinc-500 group-hover:opacity-100"
      ></div>
      <!-- 搜索按钮 -->
      <My-button
        @click="useNavigationStore.userSearchActions"
        type="primary"
        icon="search"
        class="absolute translate-y-[-50%] top-[50%] right-[7px]"
        iconColor="#ffffff"
      ></My-button>
      <!-- 历史记录列表 -->
      <Teleport to="body">
        <SearchRecordList
          v-show="showSearchHistory"
          ref="searchRecordRef"
        ></SearchRecordList>
      </Teleport>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { onClickOutside } from '@vueuse/core'
import SearchRecordList from '../search-record-list/index.vue'
import useHeaderSearchStore from '@/store/HeaderSearch/index.js'
const useNavigationStore = useHeaderSearchStore()
// 获取搜索框的输入值
const currentSearchValue = ref('')
// 控制历史记录的显示
const showSearchHistory = ref(false)

// 聚焦时显示历史记录
const onFocus = () => {
  if (currentSearchValue.value === '') {
    showSearchHistory.value = true
  }
}

// 清空搜索框内容
const cleanCurrentSearchValue = () => {
  currentSearchValue.value = ''
}
// 引入 DOM 节点引用
const parent = ref(null)

// 使用 onClickOutside 控制失焦逻辑，只在点击 input 和 history 列表外部时触发
const searchRecordRef = ref(null)
onClickOutside(
  [parent, useHeaderSearchStore.searchRecordListDom, searchRecordRef],
  () => {
    showSearchHistory.value = false
  },
  {
    ignore: [parent, useHeaderSearchStore.searchRecordListDom, searchRecordRef] // 这里使用 ignore 参数，避免点击输入框或历史记录触发外部点击逻辑
  }
)
</script>

<style lang="scss" scoped></style>
